/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.app.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import io.renren.common.validator.Assert;
import io.renren.modules.app.dao.UserDao;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.form.LoginForm;
import io.renren.modules.app.service.UserService;
import io.renren.modules.xiaoqu.entity.HouseEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.hamcrest.core.IsNull;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

	@Override
	public UserEntity queryByMobile(String mobile) {
		return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("mobile", mobile));
	}

	public UserEntity queryByUsername(String username){
		return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("username",username));
	}

	@Override
	public long login(LoginForm form) {
		form.setMobile(form.getUsername());
		UserEntity user = queryByMobile(form.getUsername());
		UserEntity user1=queryByUsername(form.getUsername());

		if (user==null){
			if (user1==null){
				//两个都没有找到
				Assert.isNull(user,"手机号或密码错误");
			}else{
				//当user没有找到，找到了user1   说明是用户名登录
				//密码错误
				if(!user1.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))){
					throw new RRException("手机号或密码错误");
				}
				return user1.getUserId();
			}
		}else {
			//当手机号找到
			//密码错误
			if(!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))){
				throw new RRException("手机号或密码错误");
			}
			return user.getUserId();
		}
		log.debug("这条日志不应该显示 ，如果显示 登录逻辑有问题");
		return 123L;
	}

	@Override
	public void delete(Integer id) {
		this.baseMapper.deleteById(id);
	}

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		IPage<UserEntity> page = this.page(
				new Query<UserEntity>().getPage(params),
				new QueryWrapper<UserEntity>()
		);
		page.getRecords().forEach(item->{
			if (item.getSex().equals("0")) {
				item.setSex("男");
			}
			else if (item.getSex().equals("1")) {
				item.setSex("女");
			}
			else {
				item.setSex("未知");
			}

			if (item.getIdentity().equals("0")) {
				item.setIdentity("admin");
			}
			else if (item.getIdentity().equals("1")) {
				item.setIdentity("管理员");
			}
			else {
				item.setIdentity("用户");
			}

			if (item.getCard().equals("0")) {
				item.setCard("否");
			}
			else {
				item.setCard("是");
			}
		});
		return new PageUtils(page);
	}
}
